package com.atguigu.tingshu.payment.service.impl;
import java.util.Date;

import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.TingShuException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private AccountFeignClient accountFeignClient;

    @Autowired
    private OrderFeignClient orderFeignClient;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public PaymentInfo savePaymentInfo(Long userId, String paymentType, String orderNo) {
        long count = this.count(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        if(count > 0){
            throw new TingShuException(400,"已存在该消费记录");
        }
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setOutTradeNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        if(SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)){
            Result<OrderInfo> orderInfoResult = orderFeignClient.getOrderInfo(orderNo);
            Assert.notNull(orderInfoResult,"订单信息不能为空，订单编号：" + orderNo);
            OrderInfo orderInfo = orderInfoResult.getData();
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setContent(orderInfo.getOrderTitle());
        }else if(SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo)){
            Result rechargeInfoResult = accountFeignClient.getRechargeInfo(orderNo);
            Assert.notNull(rechargeInfoResult,"账户信息不能为空，订单编号：" + orderNo);
            RechargeInfo rechargeInfo = (RechargeInfo)rechargeInfoResult.getData();
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent("充值金额：" + rechargeInfo.getRechargeAmount());
        }
        this.save(paymentInfo);
        return paymentInfo;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void updatePaymentInfoSuccess(Transaction transaction) {
        String orderNo = transaction.getOutTradeNo();
        PaymentInfo paymentInfo = this.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        if(paymentInfo == null){
            return;
        }
        if (paymentInfo.getPaymentStatus().equals(SystemConstant.PAYMENT_STATUS_PAID)) {
            return;
        }
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfo.setOutTradeNo(orderNo);
        this.updateById(paymentInfo);

        //更改订单状态
        if(SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())){
            Result result = orderFeignClient.orderPaySuccess(orderNo);
            if (200 != result.getCode()) {
                throw new TingShuException(500, "远程修改订单状态异常：,订单编号" + orderNo + "异常原因：" + result.getMessage());
            }
        }
        //更改充值状态
        if(SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())){
            Result result = accountFeignClient.rechargePaySuccess(orderNo);
            if (200 != result.getCode()) {
                throw new TingShuException(500, "远程修改充值订单状态异常：,订单编号" + orderNo + "异常原因：" + result.getMessage());
            }
        }

    }
}
